package com.hkts.naturalgasauthentication.management.controller;

import com.hkts.management.common.utils.IDUtils;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.naturalgasauthentication.base.controller.ManagementBaseController;
import com.hkts.naturalgasauthentication.base.service.ManagementBaseService;
import com.hkts.naturalgasauthentication.management.entity.WebsiteLogo;
import com.hkts.naturalgasauthentication.management.service.WebsiteLogoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @ClassNameWebsiteLogoController
 * @Description
 * @Author yck
 * @Date2021-02-28 19:10
 * @Version V1.0
 **/
@Controller
@RequestMapping("/authentication/websiteLogo")
public class WebsiteLogoController extends ManagementBaseController<WebsiteLogo,String> {
    @Autowired
    private WebsiteLogoService websiteLogoService;

    @Override
    public ManagementBaseService<WebsiteLogo, String> getService() {
        return websiteLogoService;
    }
    @RequestMapping("/uploadLogo")
    @ResponseBody
    public Result save(String logoId, @RequestParam(name="fileField",required=true) MultipartFile fileField) throws IOException
    {  WebsiteLogo logo=new WebsiteLogo();
        if(StringUtils.isNotBlank(logoId)){
            logo.setId(logoId);
            byte[] bytes = fileField.getBytes();
            logo.setLogo(bytes);
            websiteLogoService.update(logo);
        }else{
            logoId= IDUtils.genImageName();
            logo.setId(logoId);
            logo.setLogo(fileField.getBytes());
            websiteLogoService.save(logo);
        }
      return ResultUtil.data(logoId);
    }
    /*
    * 返回图片流
    * */
    @RequestMapping("/showImage")
    @ResponseBody
    public void showImage(String logoId , HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        WebsiteLogo websiteLogo = websiteLogoService.get(logoId);
        byte[] logo = websiteLogo.getLogo();
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(logo);
        outputStream.flush();//排出流中所有数据
        outputStream.close();//关闭流

    }

}
